package com.atguigu.tingshu.album.service.impl;

import cn.hutool.log.Log;
import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import feign.Client;
import feign.Request;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class VodServiceImpl implements VodService {

    @Autowired
    private VodConstantProperties vodConstantProperties;

    @Autowired
    private VodUploadClient vodUploadClient;

    /**
     * 将音频文件上传到腾讯云点播平台
     *
     * @param file 音频文件
     * @return {mediaFileId:"文件唯一标识",mediaUrl:"播放地址"}
     */
    @Override
    public Map<String, String> uploadTrack(MultipartFile file) {

        try {
            //1.将上传文件保存到临时上传目录下
            //UploadFileUtil.uploadTempPath() 方法接收两个参数：第一个参数是临时路径的根目录，
            // 第二个参数是要上传的文件对象。该方法会将文件保存到指定的临时路径中，并返回该文件在临时路径中的完整路径。
            String uploadTempPath = UploadFileUtil.uploadTempPath(vodConstantProperties.getTempPath(), file);

            //1.TODO 已有该对象注入即可 获取到上传客户端对象VodUploadClient

            //2.构造上传请求对象VodUploadRequest
            VodUploadRequest vodUploadRequest = new VodUploadRequest();

            vodUploadRequest.setMediaFilePath(uploadTempPath);

            //3.调用上传
            VodUploadResponse uploadResponse = vodUploadClient.upload(vodConstantProperties.getRegion(), vodUploadRequest);

            //4.封装响应结果Map
            if (uploadResponse != null) {
                Map<String, String> mapResult = new HashMap<>();
                mapResult.put("mediaFileId", uploadResponse.getFileId());
                mapResult.put("mediaUrl", uploadResponse.getMediaUrl());
                return mapResult;
            }
        } catch (Exception e) {
            log.error("[专辑服务]上传音频文件到点播平台异常:文件:{},错误信息:{}", file, e);
            throw new RuntimeException(e);
        }

        return null;
    }

    /**
     * 根据云点播平台文件唯一标识，获取音频文件详情信息
     *
     * @param mediaFileId 文件唯一标识
     * @return
     */
    @Override
    public TrackMediaInfoVo getTrackMediaInfo(String mediaFileId) {

        // 1.实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey ，此处还需要注意 密钥对 的保密
        try {
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());

            // 2.实例化要求产品的 client 对象 ，clientProfile 是可选地
            VodClient client = new VodClient(cred,vodConstantProperties.getRegion());

            // 3.实例化一个请求对象，每个接口都会对应一个 request 对象
            DescribeMediaInfosRequest request = new DescribeMediaInfosRequest();

            String[] fileIds1 = {mediaFileId};

            // 3.1 封装获取详情对应文件的唯一标识
            request.setFileIds(fileIds1);

            // 4. 调用获取文件详情接口，返回 response 是一个 DescribeMediaInfoResponse 的实例，与请求对象对应
            DescribeMediaInfosResponse response = client.DescribeMediaInfos(request);

            // 5. 解析结果对象获取音频文件时长、大小、类型
            if (response != null){
                MediaInfo[] mediaInfoSet = response.getMediaInfoSet();
                if (mediaInfoSet != null && mediaInfoSet.length > 0 ){
                    TrackMediaInfoVo vo = new TrackMediaInfoVo();
                    MediaInfo mediaInfo = mediaInfoSet[0];

                    //5.1 获取媒体文件基本信息对象
                    MediaBasicInfo basicInfo = mediaInfo.getBasicInfo();
                    vo.setType(basicInfo.getType());

                    //5.2 获取媒体文件元信息对象
                    MediaMetaData mediaMetaData = mediaInfo.getMetaData();
                    vo.setDuration(mediaMetaData.getAudioDuration());
                    vo.setSize(mediaMetaData.getSize());
                    return vo;
                }
            }
        } catch (Exception e) {
            log.error("[专辑服务]获取点播平台文件：{}，详情异常：{}",mediaFileId,e);
            throw new GuiguException(400,"音频文件详情获取异常");
        }

        return null;
    }

    /**
     * 删除云点播平台音频文件
     * @param mediaFileIdBefore
     */
    @Override
    public void deleteTrackMedia(String mediaFileIdBefore) {
        try {
            // 1.实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey
            Credential cred = new Credential(vodConstantProperties.getSecretId(),vodConstantProperties.getSecretKey());

            // 2.实例化一个请求对象，每个接口对应一个 request 对象
            DeleteMediaRequest request = new DeleteMediaRequest();
            request.setFileId(mediaFileIdBefore);

            // 3.实例化要请求产品的 client 对象，clientProfile 是可选的
            VodClient client = new VodClient(cred,vodConstantProperties.getRegion());

            // 4.返回的 response 是一个 DeleteMediaResponse 的实例 与请求对象对应
            DeleteMediaResponse response = client.DeleteMedia(request);
        } catch (TencentCloudSDKException e) {
            log.info("[专辑服务]删除云点播文件:{},失败{}",mediaFileIdBefore,e);
        }

    }
}
